package com.mxs.qrcode.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 聚合数据  https://www.juhe.cn/
 *
 * 万年历  177
 *
 */
public class HolidaysUtils {




    /**
    返回参数说明：

    名称	类型	说明
 	error_code	int	返回状态码
 	reason	string	返回原因
 	result	string	返回实体内容
 	holiday	string	当月近期假日
 	holiday_array	array	当月近期假期(数组类型)
 	status	string	1:放假,2:上班

    */

    /**
     * 聚合数据 接口每天免费100次 请申请自己的key
     */
    private static String key = "81308f3b1c47fbdd0a900a959f700559";
    private static String url = "https://v.juhe.cn/calendar/month?key=$key&year-month=";


    /**
     * 缓存月份查询对象  key 2021-1
     */
    private static Map<String, JSONObject> dataMap = new HashMap();
    /**
     * 缓存特殊日期 是否上班 key 2021-5-1  1:放假,2:上班
     */
    private static Map<String,Integer> dateStatus = new HashMap<>();

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M");
    private static SimpleDateFormat dateSdf = new SimpleDateFormat("yyyy-M-d");
    private static JSONObject getMonth(Date date){
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        Integer month = c.get(Calendar.MONTH);
        if(month == 11){
            c.add(Calendar.MONTH,-1);
        }
        return getMonth(sdf.format(c.getTime()));
    }

    /**
     * 获取月份 近期假期
     * @param month
     * @return
     */
    private static JSONObject getMonth(String month){

        if(dataMap.containsKey(month)){
            return dataMap.get(month);
        }else{
            try{
                //调用聚合数据 万年历接口
                String uri = url.replace("$key",key)+month;
                String data = load(uri);
                System.out.println(data);
                JSONObject json = (JSONObject) JSONObject.parse(data);
                if(json.getIntValue("error_code") == 0){
                    dataMap.put(month,json);
                    analysisResultJson(json);
                    return json;
                }else{
                    System.err.println("调用聚合数据 万年历接口 error_code:"+json.getIntValue("error_code"));
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 解析近期假期 返回结果  存储特殊日期状态
     * @param json
     */
    private static void analysisResultJson(JSONObject json) {
        JSONObject result = json.getJSONObject("result");
        JSONObject data = result.getJSONObject("data");
        JSONArray holiday_array = data.getJSONArray("holiday_array");

        for(int i=0;i<holiday_array.size();i++){
            JSONObject holiday = holiday_array.getJSONObject(i);
            JSONArray list = holiday.getJSONArray("list");
            for(int j=0;j<list.size();j++){
                JSONObject day = list.getJSONObject(j);
                String dateStr = day.getString("date"); //2021-1-2
                String status = day.getString("status");

                if(!dateStatus.containsKey(dateStr)){
                    dateStatus.put(dateStr,Integer.valueOf(status));
                }
            }
        }

    }

    /**
     * 调用接口
     * @param url
     * @return
     * @throws Exception
     */
    private static  String load(String url) throws Exception
    {
        URL restURL = new URL(url);
        /*
         * 此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类 的子类HttpURLConnection
         */
        HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
        //请求方式
        conn.setRequestMethod("POST");
        //设置是否从httpUrlConnection读入，默认情况下是true; httpUrlConnection.setDoInput(true);
        conn.setDoOutput(true);
        //allowUserInteraction 如果为 true，则在允许用户交互（例如弹出一个验证对话框）的上下文中对此 URL 进行检查。
        conn.setAllowUserInteraction(false);

        BufferedReader bReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String line,resultStr="";

        while(null != (line=bReader.readLine()))
        {
            resultStr +=line;
        }
        bReader.close();

        return resultStr;

    }

    /**
     * 获取日期 是否上班
     * @param date
     * @return 1:放假,2:上班
     */
    public static Integer getDateStatus(Date date){
        String dateStr = dateSdf.format(date);
        if(dateStatus.containsKey(dateStr)){
            return dateStatus.get(dateStr);
        }else{
            getMonth(date);
            if(dateStatus.containsKey(dateStr)){
                return dateStatus.get(dateStr);
            }else{
                //查看是否是周六日 不是周六日  上班
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                int week = calendar.get(Calendar.DAY_OF_WEEK);
                if(week ==1 || week ==7){
                    return 1;
                }
                return 2;
            }
        }
    }



    public static void main(String[] args) {
        //1:放假,2:上班
       /* Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH,5);
        for(int i=1;i<=30;i++){
            calendar.set(Calendar.DATE,i);
            Integer status = getDateStatus(calendar.getTime());
            if(status == 1){
                System.out.println(dateSdf.format(calendar.getTime())+":放假");
            }else{
                System.out.println(dateSdf.format(calendar.getTime())+":上班");
            }

        }*/
        Integer status = HolidaysUtils.getDateStatus(new Date());
        if(status == 1){
            System.out.println(dateSdf.format(new Date())+":放假");
        }else{
            System.out.println(dateSdf.format(new Date())+":上班");
        }
    }
}
